package com.junzhiit.nengji.cms.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.junzhiit.nengji.cms.service.ChainBrandService;
import com.junzhiit.nengji.cms.web.exception.BrandIsExistException;
import com.junzhiit.nengji.cms.web.exception.BrandNotFoundException;
import com.junzhiit.nengji.cms.web.exception.ChainNotFoundException;
import com.junzhiit.nengji.cms.web.exception.NameIsExistException;
import com.junzhiit.nengji.cms.web.util.OrderNumberUtils;
import com.junzhiit.nengji.cms.web.util.ViewObjectUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.cms.web.vo.BrandAddVO;
import com.junzhiit.nengji.cms.web.vo.BrandAllVO;
import com.junzhiit.nengji.cms.web.vo.BrandEditVO;
import com.junzhiit.nengji.cms.web.vo.BrandVO;
import com.junzhiit.nengji.cms.web.vo.DataTablesParamVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.dao.ChainBrandDAO;
import com.junzhiit.nengji.dao.ChainDAO;
import com.junzhiit.nengji.dao.cache.ChainBrandCacheDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Chain;
import com.junzhiit.nengji.model.ChainBrand;
import com.junzhiit.nengji.model.enums.LoginType;

@Service
public class ChainBrandServiceImpl extends BaseServiceImpl implements ChainBrandService{
	
	@Autowired
	private ChainBrandDAO chainBrandDAO;
	
	@Autowired
	private ChainDAO chainDAO;

	@Autowired
	private ChainBrandCacheDAO chainBrandCacheDAO;

	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;

	@Value("${upload.temp}")
	private String uploadPath;

	@Value("${upload.mall.chain.brand}")
	private String chainBrandPath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;

	@Override
	public Map<String, Object> findAll(String sessionId, DataTablesParamVO dtp, BrandVO brandVO) {
		ChainBrand chainBrand = new ChainBrand();
		BeanUtils.copyProperties(brandVO, chainBrand);
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		
		Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
		if (chain == null) {
			throw new ChainNotFoundException("连锁品牌不存在");
		}
		
		chainBrand.setChainId(chain.getId());
		
		List<ChainBrand> list = chainBrandDAO.findAll(dtp.getStart(), dtp.getLength(), chainBrand);

		List<BrandVO> listVO = new ArrayList<BrandVO>();
		for (ChainBrand param : list) {
			BrandVO vo = new BrandVO();
			BeanUtils.copyProperties(param, vo);
			listVO.add(vo);
		}

		int totalCount = chainBrandDAO.getTotalCount(chainBrand);

		return ViewObjectUtil.dataTables(listVO, dtp.getDraw(), totalCount);
	}

	@Override
	@Transactional
	public ResultVO add(String sessionId, BrandAddVO brandAddVO) {
		ResultVO resultVO = new ResultVO();
		ChainBrand chainBrand = new ChainBrand();
		BeanUtils.copyProperties(brandAddVO, chainBrand);

		String key = DIYKey.getSessionHashKey(sessionId);
		SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
		if (LoginType.SHOP.toIntType() == session.getLoginType()) {
			chainBrand.setChainId(session.getSystemId());
		}

		int count = chainBrandDAO.getBrandExist(chainBrand);
		if (count > 0) {
			throw new BrandIsExistException("品牌已经存在");
		}

		Long index = chainBrandCacheDAO.incr(DIYKey.getChainBrandCodeStringKey());
		String code = OrderNumberUtils.getSystemCode(OrderNumberUtils.BRAND_NUMBER_PREFIX, index.intValue());
		chainBrand.setCode(code);

		ChainBrand param= chainBrandDAO.insert(chainBrand);
		BrandVO brandVO=new BrandVO();
		BeanUtils.copyProperties(param, brandVO);
		resultVO.setData(brandVO);

		//FileUtil.moveFile(uploadPath + chainBrand.getLogoImgUrl(), chainBrandPath);
		boolean is = AliyunOSSClientUtil.moveFile(backetName,chainBrand.getLogoImgUrl(), chainBrandPath, uploadPath);
		if(is){
			AliyunOSSClientUtil.removeFile(backetName, uploadPath+chainBrand.getLogoImgUrl());
		}
		return resultVO;
	}

	@Override
	public ResultVO delete(String id) {
		ResultVO resultVO = new ResultVO();
		try {
			resultVO.setData(chainBrandDAO.updateToDelete(id));
		} catch (Exception e) {
			throw new BrandNotFoundException("该品牌不存在！");
		}
		return resultVO;
	}

	@Override
	@Transactional
	public ResultVO edit(BrandEditVO brandEditVO) {
		ResultVO resultVO = new ResultVO();
		ChainBrand param = chainBrandDAO.query(brandEditVO.getId());

		if (param == null) {
			throw new BrandNotFoundException("该品牌不存在！");
		}
		if (!param.getName().equals(brandEditVO.getName())) {
			ChainBrand chainBrand = new ChainBrand();
			BeanUtils.copyProperties(brandEditVO, chainBrand);
			chainBrand.setChainId(param.getChainId());
			if (chainBrandDAO.getBrandExist(chainBrand) > 0) {
				throw new NameIsExistException("品牌名称已经存在");
			}
		}
		if (StringUtils.isNotBlank(brandEditVO.getLogoImgUrl())
				&& !brandEditVO.getLogoImgUrl().equals(param.getLogoImgUrl())) {
			//FileUtil.moveFile(uploadPath + brandEditVO.getLogoImgUrl(), chainBrandPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,brandEditVO.getLogoImgUrl(), chainBrandPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+brandEditVO.getLogoImgUrl());
			}
		}

		BeanUtils.copyProperties(brandEditVO, param);
		param.setUpdatedTime(new Date());

		resultVO.setData(chainBrandDAO.update(param));
		return resultVO;
	}

	@Override
	public ResultVO findById(String id) {
		ResultVO resultVO = new ResultVO();
		ChainBrand chainBrand = chainBrandDAO.query(id);
		if (chainBrand == null) {
			throw new BrandNotFoundException("该品牌不存在！");
		}
		BrandVO brandVO = new BrandVO();
		BeanUtils.copyProperties(chainBrand, brandVO);
		resultVO.setData(brandVO);
		return resultVO;
	}

	@Override
	public ResultVO findAlls(String sessionId) {
		ResultVO resultVO = new ResultVO();
		
		String key = DIYKey.getSessionHashKey(sessionId);
		SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
		String shopId=null;
		if (LoginType.SHOP.toIntType() == session.getLoginType()) {
			shopId=session.getSystemId();
		}
		
		List<ChainBrand> brands = chainBrandDAO.findAlls(shopId);
		List<BrandAllVO> brandAllVOs = new ArrayList<BrandAllVO>();
		for (ChainBrand brand : brands) {
			BrandAllVO brandAllVO = new BrandAllVO();
			BeanUtils.copyProperties(brand, brandAllVO);
			brandAllVOs.add(brandAllVO);
		}
		resultVO.setData(brandAllVOs);
		return resultVO;
	}

	@Override
	public ResultVO delBrandPic(String id) {
		ResultVO result = new ResultVO();

		ChainBrand chainBrand = chainBrandDAO.query(id);
		if (chainBrand == null) {
			throw new BrandNotFoundException("该品牌不存在！");
		}

		//boolean flag = FileUtil.removeFile(chainBrandPath + chainBrand.getLogoImgUrl());
		boolean flag = AliyunOSSClientUtil.removeFile(backetName, chainBrandPath+chainBrand.getLogoImgUrl());
		
		chainBrand.setLogoImgUrl(null);
		chainBrand.setUpdatedTime(new Date());
		chainBrandDAO.update(chainBrand, true);

		result.setData(flag);
		return result;
	}
}
